<? // vim:set fdm=indent ts=2 ai et sts=2 sw=2 tw=0:
// simple database query class by $Author: anton $ 
// $Date: 2008-02-26T03:31:53.279063Z $
// class.db.php
// 資料庫程式 功能定義 $URL
//  Released as a GPL licensed software.

class DBData 
{
  var $name      = DEFAULT_DBNAME;
  var $hostname  = "localhost";
  var $username  = "admin";
  var $password  = "password";
  var $linkid    = NULL;
  var $encoding  = NULL;

  function INIT()
  {
    $id = @mysql_connect($this->hostname,$this->username,$this->password);
    if ($id)
    {
      $this->linkid = $id;
      $status = mysql_select_db($this->name);
    } else {
      return ERROR_CONNECTION_FAILED;
    }
    
    if (!$status)
    {
      return ERROR_DB_SELECTION_FAILED;
    } else {
      return FALSE;
    }
  }

  function END()
  {
    if ($this->linkid) $status = @mysql_close($this->linkid);
    if (!$status)
    {
      return ERROR_DB_CLOSED_FAILED;
    } else {
      return FALSE;
    }
  }

  function SQL($sql,$name=DEFAULT_DBNAME)
  {
    $ret = "";
    $data = NULL;

    if ($this->encoding)
      @mysql_query("SET NAMES '".$this->encoding."'",$this->linkid);
    else
      @mysql_query("SET NAMES 'UTF8'",$this->linkid);

    $ret = preg_match_all("/^SELECT (.*) FROM/",$sql,$match);
    if ($ret==1)
    {
      $colarr = explode(",",$match[1][0]);
      for ($i=0;$i<count($colarr);$i++)
        if (preg_match("/.*\((.*)\)/",$colarr[$i],$match))
          $colarr[$i]=$match[1];
      $colarr = str_replace("`","",$colarr);
      $colarr = str_replace(" ","",$colarr);
    } 
    $dbt = @mysql_query($sql,$this->linkid);
    if (!$dbt)
    {
      return NULL;
    }

    if ($rownum = @mysql_num_rows($dbt)) 
    {
      $data = Array();
      while (($rows = mysql_fetch_row($dbt)))
      {
        unset ($cols);
        $cols = Array();
        if ($ret==1) //有 SELECT 出來東西
        {
          for ($i=0;$i<count($colarr);$i++)
          {
            $cols[$colarr[$i]]=$rows[$i];
          }
          array_push($data,$cols);
        } else {
          array_push($data,$rows);
        }
      }
    }
    return $data;
  }

}
?>
